var child_process = require('child_process');
var querystring = require('querystring');
var fs = require('fs');
var formidable = require('formidable');
/*function requestHandler (pathname) {
	this.start = function start () {
		return 'This is start page';
	}
	this.upload = function upload () {
		return	'This is upload page';
	}
	this.index = function index () {
		return 'This is index page';
	}
}

module.exports = requestHandler;*/
//	以上通过requestHandle.start();用typeof得到的不是一个函数「function」，而是一个「undefined」

function start(res){
	res.writeHead(200 , {"Content-Type" : "text/html"});

	var body = '<html>'+
					'<head>'+
						'<title>My Test Page</title>'+
						'<meta http-equiv="Content-Type" content="text/html; charset=utf8"/>'+
						'</head>'+
					'<body>'+
						'<form name="index" action="/upload" method="post">'+
							'name:'+
							'<input type="text" name="name"><br/>'+
							'email:'+
							'<input type="text" name="email"><br/>'+
							'address:'+
							'<input type="text" name="address"><br/>'+
							'<textarea name="text" rows="20" cols="60"></textarea>'+
							'<input type="submit" value="Submit">'+
						'</form>'+
					'</body>'+
				'</html>';
	res.write(body);
	res.end();
}	

function upload (res,postData) {
	var data = querystring.parse(postData);
	var name = data.name;
	var email = data.email;
	var address = data.address;
	res.writeHead(200 , {"Content-Type":"text/html"});
	res.write('name is '+ name);
	res.write('<img src="/show" />');
	res.end();
}

function lsFiles (res) {
	var exec = child_process.exec;
//	var content = "empty";
	exec("ls -a" , function  (error , stdout , stderr) {
		res.writeHead(200 , {"Content-Type":"text/html"});
		res.write(stdout);
		res.end();
	});
}

function show (res,postData) {
	fs.readFile("/Users/pengloo53/Pictures/hello.jpg", "binary" , function (error,file) {
		if(error){
			res.writeHead(500 , {"Content-Type":"text/html"});
			res.write(error + "\n");
			res.end();
		}else{
			res.writeHead(200 , {"Content-Type":"image/jpg"});
			res.write(file,'binary');
			res.end();
		}
	});
}

exports.start = start;
exports.upload = upload;
exports.lsFiles = lsFiles;
exports.show = show;
